<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500px"
    @close="handleClose"
  >
    <div class="folder-select-container">
      <el-input
        v-model="filterText"
        placeholder="搜索文件夹"
        :prefix-icon="Search"
        clearable
        class="search-input"
      />
      
      <el-tree
        ref="treeRef"
        :data="filteredFolders"
        :props="treeProps"
        :filter-node-method="filterNode"
        node-key="folderId"
        :highlight-current="true"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        class="folder-tree"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <el-icon class="folder-icon">
              <Folder v-if="!node.isLeaf" />
              <FolderOpened v-else />
            </el-icon>
            <span class="node-label">{{ node.label }}</span>
          </div>
        </template>
      </el-tree>
      
      <div v-if="selectedFolder" class="selected-folder">
        已选择: <span class="folder-name">{{ selectedFolder.folderName }}</span>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="!selectedFolder"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { Folder, FolderOpened, Search } from '@element-plus/icons-vue'
import type { CdFolderVo } from '@/types/cd'
import { folderApi } from '@/api/cd'

interface Props {
  visible: boolean
  title: string
  excludeFolderId?: number | string
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'confirm', folderId: number | string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = ref(false)
const filterText = ref('')
const treeRef = ref()
const selectedFolder = ref<CdFolderVo | null>(null)
const folders = ref<CdFolderVo[]>([])

const treeProps = {
  children: 'children',
  label: 'folderName'
}

// 过滤后的文件夹树
const filteredFolders = computed(() => {
  if (!filterText.value) {
    return props.excludeFolderId ? excludeFolder(folders.value) : folders.value
  }
  
  // 过滤逻辑
  const filter = (nodes: CdFolderVo[]): CdFolderVo[] => {
    return nodes.filter(node => {
      if (node.folderName.toLowerCase().includes(filterText.value.toLowerCase())) {
        return true
      }
      if (node.children && node.children.length > 0) {
        node.children = filter(node.children)
        return node.children.length > 0
      }
      return false
    })
  }
  
  return filter(props.excludeFolderId ? excludeFolder(folders.value) : folders.value)
})

// 排除指定文件夹
const excludeFolder = (nodes: CdFolderVo[]): CdFolderVo[] => {
  const excludeId = String(props.excludeFolderId)
  return nodes.filter(node => {
    if (String(node.folderId) === excludeId) {
      return false
    }
    if (node.children && node.children.length > 0) {
      node.children = excludeFolder(node.children)
    }
    return true
  })
}

// 监听弹窗显示状态
watch(() => props.visible, async (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    await loadFolderTree()
    selectedFolder.value = null
    filterText.value = ''
  }
})

// 监听过滤文本变化
watch(filterText, (val) => {
  treeRef.value?.filter(val)
})

const loadFolderTree = async () => {
  try {
    const response = await folderApi.getTree(1) // TODO: 从用户store获取实际用户ID
    folders.value = response.data || []
  } catch (error) {
    console.error('加载文件夹树失败:', error)
  }
}

const filterNode = (value: string, data: CdFolderVo) => {
  if (!value) return true
  return data.folderName.toLowerCase().includes(value.toLowerCase())
}

const handleNodeClick = (data: CdFolderVo) => {
  selectedFolder.value = data
}

const handleClose = () => {
  emit('update:visible', false)
}

const handleConfirm = () => {
  if (selectedFolder.value) {
    emit('confirm', String(selectedFolder.value.folderId))
    handleClose()
  }
}
</script>

<style scoped lang="scss">
.folder-select-container {
  .search-input {
    margin-bottom: 16px;
  }
  
  .folder-tree {
    height: 300px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px;
    
    :deep(.el-tree-node__content) {
      height: 36px;
      padding: 0 8px;
      border-radius: 4px;
      margin: 2px 0;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.is-current {
        background-color: #e6f7ff;
        color: #1890ff;
      }
    }
  }
  
  .selected-folder {
    margin-top: 16px;
    padding: 12px;
    background-color: #f0f9ff;
    border-radius: 4px;
    border: 1px solid #b3d8ff;
    
    .folder-name {
      color: #1890ff;
      font-weight: 500;
    }
  }
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  
  .folder-icon {
    margin-right: 8px;
    color: #409eff;
  }
  
  .node-label {
    flex: 1;
    font-size: 14px;
  }
}
</style>
